<?php

namespace App\Http\Controllers;

use App\Models\NewTemplate;
use Illuminate\Http\Request;

class NewTemplateController extends Controller {

    public function index(Request $request) {
        $input = $request->all();
        $brand = $input['brand'];
        $templates = NewTemplate::select('time', 'invalid', 'advantage', 'condition', 'introduce')
                ->where('invalid', false)
                ->inRandomOrder()->take(1)->get();
        $data = [];
        $template = $templates[0];
        $data['advantage'] = $this->formatContent($template->advantage, $brand);
        $data['condition'] = $this->formatContent($template->condition, $brand);
        $data['introduce'] = $this->formatContent($template->introduce, $brand);
        $template->time = $template->time + 1;
        if($template->time >= 5) {
            $template->invalid = true;
        }
        $template->save();
        return json_encode($data,320);
    }
    
    private function formatContent($content, $name) {
        $format = str_replace("{name}", $name, $content);
        return $format;
    }
}
